package test.wordprj.word.uitl;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

public class TreeCellMergeStrategy implements CellWriteHandler {

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
                                 List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (isHead) return;

        int columnIndex = cell.getColumnIndex();
        int rowIndex = cell.getRowIndex();
        Sheet sheet = writeSheetHolder.getSheet();

        // 合并规则：从当前行开始，向下查找相同父级的行数
        if (columnIndex == 0) { // 合并一级功能列
            mergeSameParent(sheet, rowIndex, columnIndex, 0);
        } else if (columnIndex == 1) { // 合并二级功能列
            mergeSameParent(sheet, rowIndex, columnIndex, 1);
        }
        // 其他层级类似...
    }

    private void mergeSameParent(Sheet sheet, int rowIndex, int columnIndex, int checkColumn) {
        String currentValue = getCellValue(sheet, rowIndex, checkColumn);
        int startRow = rowIndex;
        int endRow = rowIndex;

        // 向上查找起始行
        while (startRow > 0 && currentValue.equals(getCellValue(sheet, startRow - 1, checkColumn))) {
            startRow--;
        }

        // 向下查找结束行
        while (endRow < sheet.getLastRowNum() && currentValue.equals(getCellValue(sheet, endRow + 1, checkColumn))) {
            endRow++;
        }

        if (startRow < endRow) {
            CellRangeAddress region = new CellRangeAddress(startRow, endRow, columnIndex, columnIndex);
           // sheet.addMergedRegion(region);
        }
    }

    private String getCellValue(Sheet sheet, int rowIndex, int column) {
        Row row = sheet.getRow(rowIndex);
        if (row == null) return "";
        Cell cell = row.getCell(column);
        return cell != null ? cell.getStringCellValue() : "";
    }
}

